<template>
  <div class="user-management">
    <el-card class="shadow-lg" style="border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.08);">
      <template #header>
        <div class="card-header d-flex justify-between items-center">
          <div class="d-flex items-center">
            <i class="el-icon-user-solid mr-2 text-primary"></i>
            <span class="text-lg font-medium">用户管理</span>
          </div>
          <!-- 搜索框 -->
          <div class="search-box">
            <el-input
                v-model="searchUsername"
                placeholder="请输入用户名搜索"
                clearable
                @keyup.enter.native="fetchUsers"
                suffix-icon="el-icon-search"
                style="width: 200px"
            />
            <el-button @click="openAddUserDialog" type="success" icon="el-icon-plus">新增用户</el-button>
            <el-button @click="fetchUsers" type="primary" icon="el-icon-search">搜索</el-button>
          </div>
        </div>
      </template>

      <div class="table-container">
        <el-table
            :data="userList"
            stripe
            style="width: 100%"
            class="user-table"
            v-loading="loading"
            element-loading-text="加载中..."
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.1)"
        >
          <el-table-column prop="id" label="ID" width="80" show-overflow-tooltip />
          <el-table-column prop="username" label="用户名" width="120" show-overflow-tooltip />
          <el-table-column label="密码" width="200" show-overflow-tooltip>
            <template slot-scope="{ row }">
              <span>{{ row.password ? '●●●●●●●●' : '-' }}</span>
            </template>
          </el-table-column>

          <!-- 👇 新增列 -->
          <el-table-column prop="isLeader" label="用户类型" width="140">
            <template slot-scope="{ row }">
              <el-tag :type="row.isLeader === 1 ? 'success' : 'info'" size="small">
                <i class="el-icon-user mr-1"></i>
                {{ row.isLeader === 1 ? '管理员' : '普通用户' }}
              </el-tag>
            </template>
          </el-table-column>
          <!-- 👆 新增列 -->

          <el-table-column prop="createTime" label="创建时间" width="180">
            <template slot-scope="{ row }">
              <span>{{ formatDate(row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="更新时间" width="180">
            <template slot-scope="{ row }">
              <span>{{ formatDate(row.updateTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="{ row }">
              <el-button
                  size="small"
                  type="primary"
                  plain
                  @click="openEditDialog(row)"
                  icon="el-icon-edit"
                  circle
              />
              <el-button
                  size="small"
                  type="danger"
                  plain
                  @click="deleteUser(row.id)"
                  icon="el-icon-delete"
                  circle
              />
            </template>
          </el-table-column>
        </el-table>

      </div>

      <!-- 编辑用户对话框 -->
      <!-- 编辑用户对话框 -->
      <el-dialog
          :visible.sync="dialogVisible"
          title="编辑用户"
          width="400px"
          :before-close="handleDialogClose"
          custom-class="custom-dialog"
      >
        <el-form ref="formRef" :model="editForm" :rules="rules" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username" disabled />
          </el-form-item>
          <el-form-item label="新密码" prop="password">
            <el-input
                v-model="editForm.password"
                type="password"
                placeholder="留空则不修改密码"
            />
          </el-form-item>

          <!-- 👇 新增字段：用户类型 -->
          <el-form-item label="用户类型" prop="isLeader">
            <el-select v-model="editForm.isLeader" placeholder="请选择用户类型" style="width: 100%">
              <el-option label="普通用户" :value="0" />
              <el-option label="管理员" :value="1" />
            </el-select>
          </el-form-item>
          <!-- 👆 新增字段 -->

        </el-form>
        <template #footer>
    <span class="dialog-footer">
      <el-button @click="handleDialogClose">取消</el-button>
      <el-button type="primary" @click="submitEdit">确认修改</el-button>
    </span>
        </template>
      </el-dialog>


      <!-- 新增用户对话框 -->
      <el-dialog
          :visible.sync="addDialogVisible"
          title="新增用户"
          width="400px"
          :before-close="handleAddDialogClose"
          custom-class="custom-dialog"
      >
        <el-form ref="addFormRef" :model="addForm" :rules="addRules" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password" type="password" show-password />
          </el-form-item>
          <el-form-item label="用户类型" prop="isLeader">
            <el-select v-model="editForm.isLeader" placeholder="请选择用户类型" style="width: 100%">
              <el-option label="普通用户" :value="0" />
              <el-option label="管理员" :value="1" />
            </el-select>
          </el-form-item>

        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="handleAddDialogClose">取消</el-button>
            <el-button type="primary" @click="submitAddUser">确认新增</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 空状态提示 -->
      <div v-if="userList.length === 0" class="empty-state">
        <i class="el-icon-s-empty text-gray-300 text-5xl mb-4"></i>
        <p class="text-gray-500 mb-2">暂无用户数据</p>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "UserManagement",
  components: {},
  data() {
    return {
      userList: [],         // 用户列表
      searchUsername: "",   // 搜索关键词
      loading: false,       // 加载状态
      dialogVisible: false, // 编辑弹窗
      addDialogVisible: false, // 新增弹窗
      editForm: {
        id: null,
        username: "",
        password: "",
        isLeader: 0 // 新增字段
      },
      addForm: {            // 新增表单数据
        username: "",
        password: "",
        isLeader: 0         // 默认是普通用户
      },
      rules: {
        password: [
          { min: 6, message: '密码长度至少6位', trigger: 'blur' }
        ],
        isLeader: [
          { required: true, message: '请选择用户类型', trigger: 'change' }
        ]
      },
      addRules: {            // 新增验证规则
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, message: '密码长度至少6位', trigger: 'blur' }
        ],
        isLeader: [
          { required: true, message: '请选择用户类型', trigger: 'change' }
        ]
      }
    };
  },
  watch: {
    dialogVisible(newVal, oldVal) {
      console.log('dialogVisible 状态变化:', oldVal, '->', newVal);
    }
  },
  mounted() {
    this.fetchUsers(); // 组件挂载后获取用户数据
  },
  methods: {
    fetchUsers() {
      this.loading = true;
      const params = this.searchUsername.trim() ? { username: this.searchUsername.trim() } : {};

      this.$request.get('/getUser', { params })
          .then(response => {
            if (response && response.code === 200) {
              this.userList = response.data || [];
            } else {
              this.userList = [];
              this.$message.error(response.message || '获取用户失败');
            }
          })
          .catch(error => {
            console.error('获取用户失败:', error);
            this.$message.error('网络错误，请稍后重试');
            this.userList = [];
          })
          .finally(() => {
            this.loading = false;
          });
    },

    openEditDialog(row) {
      this.editForm = {
        id: row.id,
        username: row.username,
        password: "",
        isLeader: row.isLeader // 确保这行存在，表示用户类型
      };
      this.$refs.formRef && this.$refs.formRef.resetFields();
      this.dialogVisible = true;
    },



    submitEdit() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.loading = true;

          const params = {
            id: this.editForm.id,
            isLeader: this.editForm.isLeader
          };

          if (this.editForm.password) {
            params.password = this.editForm.password;
          }

          this.$request.post(`/updateUser`, params)
              .then(response => {
                if (response && response.code === 200) {
                  this.$message.success('用户信息更新成功');
                  this.dialogVisible = false;
                  this.fetchUsers();
                } else {
                  this.$message.error(response.message || '更新用户失败');
                }
              })
              .catch(error => {
                console.error('更新用户失败:', error);
                this.$message.error('网络错误，请稍后重试');
              })
              .finally(() => {
                this.loading = false;
              });
        }
      });
    },


    handleDialogClose() {
      this.$refs.formRef && this.$refs.formRef.resetFields();
      this.dialogVisible = false;
    },

    openAddUserDialog() {
      this.addForm = {
        username: '',
        password: '',
        isLeader: 0
      };
      this.$refs.addFormRef && this.$refs.addFormRef.resetFields();
      this.addDialogVisible = true;
    },

    submitAddUser() {
      this.$refs.addFormRef.validate(valid => {
        if (valid) {
          this.loading = true;
          const params = {
            username: this.addForm.username,
            password: this.addForm.password,
            isLeader: this.addForm.isLeader
          };

          this.$request.post('/addUserByAdmin', params)
              .then(response => {
                if (response && response.code === 200) {
                  this.$message.success('用户添加成功');
                  this.addDialogVisible = false;
                  this.fetchUsers();
                } else {
                  this.$message.error(response.message || '添加用户失败');
                }
              })
              .catch(error => {
                console.error('添加用户失败:', error);
                this.$message.error('网络错误，请稍后重试');
              })
              .finally(() => {
                this.loading = false;
              });
        }
      });
    },

    handleAddDialogClose() {
      this.$refs.addFormRef && this.$refs.addFormRef.resetFields();
      this.addDialogVisible = false;
    },

    deleteUser(id) {
      this.$confirm('确定要删除该用户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        this.$request.get('/deleteUser', { params: { id } })
            .then(response => {
              if (response && response.code === 200) {
                this.$message.success('用户删除成功');
                this.fetchUsers();
              } else {
                this.$message.error(response.message || '删除用户失败');
              }
            })
            .catch(error => {
              console.error('删除用户失败:', error);
              this.$message.error('网络错误，请稍后重试');
            })
            .finally(() => {
              this.loading = false;
            });
      }).catch(() => {});
    },

    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toLocaleDateString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit"
      });
    }
  }
};
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.card-header {
  font-size: 16px;
  font-weight: 600;
}

.search-box {
  display: flex;
  align-items: center;
  gap: 10px;
}

.table-container {
  margin-top: 10px;
}

.user-table ::v-deep .el-table__cell {
  padding: 10px 0;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
  color: #999;
}

.empty-state i {
  font-size: 60px;
  color: #e0e0e0;
}

::v-deep .custom-dialog {
  border-radius: 12px;
  overflow: hidden;
}

::v-deep .custom-dialog .el-dialog__header {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

::v-deep .custom-dialog .el-dialog__footer {
  background-color: #f9fafb;
  text-align: right;
}
</style>
